var GuideCrawler = function() {
	/**
	 * constant values
	 */
	var DEF_URL_LIST = 'list_url';
	var DEF_SERVER_URL = 'server_url';
	
	/**
	 * preference key
	 */
	var PREF_HOST_NAME = 'host_name';
	
	/**
	 * Control IDs
	 */
	var CTR_URL_LIST = 'list_url';
	var CTR_HTML     = 'id_html';
	
	/**
	 * properties
	 */
	var serverUrl;

	/**
	 * urls
	 */
	var urls = new Array();

	var HIGH_LIGHTED_STYLE = "2px solid red";
		
	var oldStyle;
	
	var labelItems = new Array();
                 
	/**
	 * methods
	 */
	var initServerUrl = function() {
		var prefManager = Components.classes["@mozilla.org/preferences-service;1"]
				.getService(Components.interfaces.nsIPrefBranch);

		serverUrl = prefManager.getCharPref(PREF_HOST_NAME);
		
		document.getElementById(DEF_SERVER_URL).value = serverUrl;
	};
	
	var addUrl = function (website) {
		urls.push(website);
		document.getElementById(CTR_URL_LIST).appendItem (website.label, website.url);
		
		setHtmlText ("Add [" + website.label + " | " + website.url + "]");
	}
	
	var setHtmlText = function (text) {
		document.getElementById(CTR_HTML).value = text;
	}
	
	var getValidParentNode = function (n) {
		if (n == null) {
			return null;
		}
		for (node = n; node = node.parentNode; node != getBrowser().contentWindow.document) {
			if (node.nodeType == Node.ELEMENT_NODE ||
			    node.nodeType == Node.ATTRIBUTE_NODE) {
				return node;
			}
		}
		
		return null;
	}
	
	var refresh = function () {
		disableLinks();
		getBrowser().contentWindow.addEventListener("mouseup", eveMouseUp, false);
	}
	
	var getBrowser = function () {
		return document.getElementById('id_browser');
	}
	
	var nodeToStr = function(node) {
		var str = node.nodeName;
		
		str += " {";
		for (var i = node.attributes.length - 1; i >= 0; i--) {
			if ('class' == node.attributes[i].name.toLowerCase() || 'id' == node.attributes[i].name.toLowerCase()) {
				str += node.attributes[i].name + "=" + node.attributes[i].value;
				if (i != 0) {
					str += ", "
				}
			}
		}
		str += "}";
		return str;
	};

	var getXPath = function(element) {
	    if (element.id!=='')
	        return 'id("'+element.id+'")';
	    if (element===document.body)
	        return element.tagName;
	
	    var ix= 0;
	    var siblings= element.parentNode.childNodes;
	    for (var i= 0; i<siblings.length; i++) {
	        var sibling= siblings[i];
	        if (sibling===element)
	            return getPathTo(element.parentNode)+'/'+element.tagName+'['+(ix+1)+']';
	        if (sibling.nodeType===1 && sibling.tagName===element.tagName)
	            ix++;
	    }
	};
	
	var selectNode = function(labelName, node) {
		xpath = getXPath (node);
		labelItem = labelItems[xpath];
		
		alert("XPATH[" + xpath +"]");
		if (null != labelItem) {
			// existed node
			node.style.border = labelItem['oldstyle']; // restore the old style;
			alert("OLD STYLE:" + labelItem['oldstyle']);
			labelItems[xpath] = null;
			
			return false;
		} else {
			alert("running3");
			labelItem = new Array();
			labelItem['oldstyle'] = node.style.border;
			labelItem['node']     = node;
				
			node.style.border = HIGH_LIGHTED_STYLE;  // can be used for auto generated style
			labelItems[xpath] = labelItem;
			
			return true;
		}
	};
	
	var disableLinks = function() {
		var as = getBrowser().contentDocument.getElementsByTagName('a');
		for (var i = 0; i < as.length; i++) {
			as[i].addEventListener('click', function(e) {
						if (e && e.preventDefault) {
							e.preventDefault();
						}
					}, false);
		}
	}
  
	var eveMouseUp = function (event) {
		if (event.pageX >= getBrowser().contentDocument.body.clientWidth
			|| event.pageY >= getBrowser().contentDocument.body.clientHeight) {
			return;
		}
			
		/*
			var w = getBrowser().contentWindow;
			var sel = w.getSelection();
		*/
		var node = event.explicitOriginalTarget||event.srcElement||document.activeElement;
		
		node = getValidParentNode (node);
		if (null == node) {
			return;
		}
		
		if (selectNode ("testKey", node)) {
			setHtmlText ("Selected:[" + node.textContent + "]");
		} else {
			setHtmlText ("DeSelected:[" + node.textContent + "]");
		}
	}
	
	return {
		init : function () {
			initServerUrl();
		},
		
		saveServerUrl : function () {
			var prefManager = Components.classes["@mozilla.org/preferences-service;1"]
					.getService(Components.interfaces.nsIPrefBranch);
	
			serverUrl = document.getElementById(DEF_SERVER_URL).value;	
			
			prefManager.setCharPref(PREF_HOST_NAME, serverUrl);
		},
		
		openUrl : function () {
			getBrowser().contentWindow.location=document.getElementById('list_url').getSelectedItem(0).value;
			
			getBrowser().addEventListener("load", refresh, false);
		},
		
		addNewWebSite : function () {
			returnValue = { out : null };  
	  
			window.openDialog(  
	  			"chrome://GuideCrawler/content/AddWebSite.xul",  
	  			"dlgAddNewWebSite", "chrome, dialog, modal, resizable=no", returnValue);
	  		
	  		if (returnValue.out) {
	  			addUrl (returnValue.out);
	  		}
		}
	}
}();

window.addEventListener("load", GuideCrawler.init, false);
